<?php

namespace app\admin\controller\litestore;

use app\common\controller\Backend;
use app\admin\model\litestore\Litestorespec as SpecModel;
use app\admin\model\litestore\Litestorespecvalue as SpecValueModel;
use fast\Tree;
use think\Db;
use addons\litestore\model\Wxlitestoregoods;
use addons\litestore\model\Litestoregoodsspec;


use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use addons\faqueue\library\QueueApi;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Litestoregoods extends Backend
{
    private $SpecModel;
    private $SpecValueModel;
    /**
     * Litestoregoods模型对象
     * @var \app\admin\model\Litestoregoods
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->SpecModel = new SpecModel;
        $this->SpecValueModel = new SpecValueModel;

        $this->model = new \app\admin\model\litestore\Litestoregoods;
        $this->view->assign("specTypeList", $this->model->getSpecTypeList());
        $this->view->assign("deductStockTypeList", $this->model->getDeductStockTypeList());
        $this->view->assign("goodsStatusList", $this->model->getGoodsStatusList());
        $this->view->assign("isDeleteList", $this->model->getIsDeleteList());
        $this->view->assign("isTuijianList", $this->model->getIsTuijianList());
        $this->view->assign("isZhekouList", $this->model->getIsZhekouTypeList());
        $this->view->assign("homelist", $this->model->getHomeList());

        $this->view->assign("spec_attr", '');
        $this->view->assign("spec_list", '');
        $Litestorecategory = new \app\admin\model\litestore\Litestorecategory;
        $tree = Tree::instance();
        $tree->nbsp = "";
        $tree->init(collection($Litestorecategory->order('weigh desc,id desc')->select())->toArray(), 'pid');
        $this->categorylist = $tree->getTreeList($tree->getTreeArray(0), 'name');
        $categorydata = [];
        foreach ($this->categorylist as $k => $v)
        {
            $categorydata[$v['id']] = $v;
        }
        
        $categorylist2 =$tree->getTreeArray(0, 'name');
     
 
        $this->assignconfig('typeList', $categorylist2);
        $this->view->assign("parentList", $categorydata);
    }


    
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    
    /**
     * 查看
     */
    public function guoqi()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            
            $total = $this->model
                    ->with(['category','freight'])
                    ->where($where)
                   
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->with(['category','freight'])
                    ->where($where)
                  
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                
                $row->getRelation('category')->visible(['name']);
                $row->getRelation('freight')->visible(['name']);
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $map2['is_jifen'] = 0;
            $map2['is_kan'] = 0;
            $total = $this->model
                    ->with(['category','freight','gongyingshang'])
                    ->where($where)
                    ->where($map2)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->with(['category','freight','gongyingshang'])
                    ->where($where)
                    ->where($map2)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                
                $row->getRelation('category')->visible(['name']);
                $row->getRelation('freight')->visible(['name']);
                // $row->getRelation('shangjia')->visible(['name']);
                $row->getRelation('gongyingshang')->visible(['name']);
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 查看
     */
    public function index2()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $map2['is_jifen'] = 1;
            $total = $this->model
                    ->with(['category','freight'])
                    ->where($where)
                    ->where($map2)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->with(['category','freight'])
                    ->where($where)
                    ->where($map2)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                
                $row->getRelation('category')->visible(['name']);
                $row->getRelation('freight')->visible(['name']);
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 查看
     */
    public function index3()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $map2['is_kan'] = 1;
            $total = $this->model
                    ->with(['category','freight'])
                    ->where($where)
                    ->where($map2)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->with(['category','freight'])
                    ->where($where)
                    ->where($map2)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                
                $row->getRelation('category')->visible(['name']);
                $row->getRelation('freight')->visible(['name']);
            }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    public function addSpec($spec_name, $spec_value){
         // 判断规格组是否存在
        if (!$specId = $this->SpecModel->getSpecIdByName($spec_name)) {
            // 新增规格组and规则值
            if ($this->SpecModel->add($spec_name)
                && $this->SpecValueModel->add($this->SpecModel['id'], $spec_value))
                return $this->success('', '', [
                    'spec_id' => (int)$this->SpecModel['id'],
                    'spec_value_id' => (int)$this->SpecValueModel['id'],
                ]);
            return $this->error();
        }
        //return ;
        // 判断规格值是否存在
        if ($specValueId = $this->SpecValueModel->getSpecValueIdByName($specId, $spec_value)) {
            return $this->success('', '', [
                'spec_id' => (int)$specId,
                'spec_value_id' => (int)$specValueId,
            ]);
        }
        // 添加规则值
        if ($this->SpecValueModel->add($specId, $spec_value))
            return $this->success('', '', [
                'spec_id' => (int)$specId,
                'spec_value_id' => (int)$this->SpecValueModel['id'],
            ]);
        return $this->error();
    }


    /**
     * 添加规格值
     */
    public function addSpecValue($spec_id, $spec_value)
    {
        // 判断规格值是否存在
        if ($specValueId = $this->SpecValueModel->getSpecValueIdByName($spec_id, $spec_value)) {
            return $this->success('', '', [
                'spec_value_id' => (int)$specValueId,
            ]);
        }
        // 添加规则值
        if ($this->SpecValueModel->add($spec_id, $spec_value))
            return $this->success('', '', [
                'spec_value_id' => (int)$this->SpecValueModel['id'],
            ]);
        return $this->error();
    }

    /**
     * 添加
     */
    public function add()
    {   


        $baojia = Db::table('fa_pifa_baojia')->select();
        $shangjia = Db::table('fa_pifa_shangjia')->select();

        $this->view->assign('baojia', $baojia);
        $this->view->assign('shangjia', $shangjia);
        $this->assignconfig('baojia', $baojia);
        $this->assignconfig('shangjia', $shangjia);
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                    
                
                // if ($params['spec_type'] === '20') {
                //     if (!isset($params['spec_list'])) {
                //       $this->error('请上传规格数据');
                //     }
                //     if (!isset($params['spec_many'])) {
                //       $this->error('请上传规格数据');
                //     }
                // }
                
                
                
                
                
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
                        $this->model->validate($validate);
                    }

                    if (!empty($params['en_time'])) {
                        $params['en_time'] = strtotime($params['en_time']);
                    }

                    if (empty($params['daoqi'])) {
                        $params['daoqi'] = date('Y-m-d');
                    }
                    $spec_many_params = $this->request->post("spec_many/a");
                    $spec_a = $this->request->post("spec/a");
                    $baojia_spec = $this->request->post("baojia_spec/a");
                    $baojia_quyu = $this->request->post("baojia_quyu/a");
                    $baojia_xiangou = $this->request->post("baojia_xiangou/a");
                    $baojia_allow = $this->request->post("baojia_allow/a");

                    
                    $baojia_dan['baojia'] = json_encode($baojia_spec);
                    $baojia_dan['baojia_xiangou'] = json_encode($baojia_xiangou);
                    $baojia_dinghuo2 = [];

                    foreach ($baojia_spec as $key => $value) {
                        $baojia_dinghuo2[$key] = 0;

                        if (isset($baojia_allow[$key])) {
                            $baojia_dinghuo2[$key] = $baojia_allow[$key];
                        }
                    }
                    $baojia_dan['baojia_dinghuo'] = json_encode($baojia_dinghuo2);

                    $spec_a['baojia'] = $baojia_dan['baojia'];
                    $spec_a['baojia_quyu'] = json_encode($baojia_quyu);
                    $spec_a['dinghuo'] = $baojia_dan['baojia_dinghuo'];
                    $spec_a['xiangou'] = $baojia_dan['baojia_xiangou'];


                  
                   
                  
                    $result = $this->model->allowField(true)->save($params);
                    if ($result !== false) {
                        //成功之后 存储商品规格
                        // $spec_many_params = $this->request->post("spec_many/a");

                        // var_dump($spec_many_params);
                        $this->model->addGoodsSpec($params,$spec_many_params,$spec_a);
                        $this->success();
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add2()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    if ($result !== false) {
                        //成功之后 存储商品规格
                        $spec_many_params = $this->request->post("spec_many/a");
                        $this->model->addGoodsSpec($params,$spec_many_params,$this->request->post("spec/a"));
                        $this->success();
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

     /**
     * 添加
     */
    public function add3()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : true) : $this->modelValidate;
                        $this->model->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    if ($result !== false) {
                        //成功之后 存储商品规格

                        // var_dump(1);
                        $spec_many_params = $this->request->post("spec_many/a");
                        $this->model->addGoodsSpec($params,$spec_many_params,$this->request->post("spec/a"));
                        $this->success();
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $count = $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();
            $count = 0;
            foreach ($list as $k => $v) {
                // 删除商品sku
                $v->removesku();

                $count += $v->delete();
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {   


        $baojia = Db::table('fa_pifa_baojia')->select();

        $this->view->assign('baojia', $baojia);

        $shangjia = Db::table('fa_pifa_shangjia')->select();



        $baojia2 = $baojia;
        foreach ($baojia2 as $key => $value) {
            $baojia2[$key]['baojia'] = 0;
            $baojia2[$key]['xiangou'] = 0;
            $baojia2[$key]['dinghuo'] = 0;
        }


         foreach ($shangjia as $key => $value) {
            $shangjia[$key]['baojia'] = 0;
        }
         $this->view->assign('shangjia', $shangjia);

        $this->assignconfig('baojia', $baojia);
        $this->assignconfig('shangjia', $shangjia);
        $row = $this->model->get($ids, ['specRel', 'spec', 'spec_rel.spec']);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");


            $result['params'] = $params;
            $result['spec'] = $this->request->post("spec/a");

          
            if ($params) {
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
                        $row->validate($validate);
                    }

                    if (!empty($params['en_time'])) {
                        $params['en_time'] = strtotime($params['en_time']);
                    }

                    if (empty($params['daoqi'])) {
                        $params['daoqi'] = date('Y-m-d');
                    }


                    $spec_a = $this->request->post("spec/a");
                    $baojia_spec = $this->request->post("baojia_spec/a");
                    $baojia_quyu = $this->request->post("baojia_quyu/a");
                    $baojia_xiangou = $this->request->post("baojia_xiangou/a");
                    $baojia_allow = $this->request->post("baojia_allow/a");

                    
                    $baojia_dan['baojia'] = json_encode($baojia_spec);
                    $baojia_dan['baojia_xiangou'] = json_encode($baojia_xiangou);
                    $baojia_dinghuo2 = [];

                    foreach ($baojia_spec as $key => $value) {
                        $baojia_dinghuo2[$key] = 0;

                        if (isset($baojia_allow[$key])) {
                            $baojia_dinghuo2[$key] = $baojia_allow[$key];
                        }
                    }
                    $baojia_dan['baojia_dinghuo'] = json_encode($baojia_dinghuo2);

                    $spec_a['baojia'] = $baojia_dan['baojia'];
                    $spec_a['dinghuo'] = $baojia_dan['baojia_dinghuo'];
                    $spec_a['baojia_quyu'] = json_encode($baojia_quyu);
                    $spec_a['xiangou'] = $baojia_dan['baojia_xiangou'];



                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        //成功之后 存储商品规格
                        $spec_many_params = $this->request->post("spec_many/a");

                       
                        $row->addGoodsSpec($params,$spec_many_params,$spec_a, true);
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        // 多规格信息
        $specData = 'null';
        if ($row['spec_type'] === '20'){
            $specData = json_encode($this->model->getManySpecData($row['spec_rel'], $row['spec']));
            $baojia_list = [];
            $shangjia_list = [];
            $baojia = Db::table('fa_pifa_baojia')->select();

            $bajia_num = [];
            $bajia_num2 = [];

            foreach ($baojia as $key => $value) {
                $bajia_num[$value['id']] = 0;
            }

            foreach ($shangjia as $key => $value) {
                $bajia_num2[$value['id']] = 0;
            }

            $specData = json_decode($specData,true);
            foreach ($specData['spec_list'] as $key => $value) {


                 $baojia_list[$key]['spec_key'] = $value['spec_sku_id'];
                 $baojia_list[$key]['spec_text'] = getSpecNameBySkuArr($value['goods_sku_id_arr'],$specData['spec_attr']);
                 $baojia_list[$key]['user_group'] = !empty($value['form']['baojia']) ? $value['form']['baojia'] : $bajia_num;
                 $baojia_list[$key]['xiangou'] = !empty($value['form']['xiangou']) ? $value['form']['xiangou'] : $bajia_num;
                 $baojia_list[$key]['dinghuo'] = !empty($value['form']['dinghuo']) ? $value['form']['dinghuo'] : $bajia_num;


                $shangjia_list[$key]['spec_key'] = $value['spec_sku_id'];
                $shangjia_list[$key]['spec_text'] = getSpecNameBySkuArr($value['goods_sku_id_arr'],$specData['spec_attr']);
                $shangjia_list[$key]['user_group'] = !empty($value['form']['baojia_quyu']) ? $value['form']['baojia_quyu'] : $bajia_num2;
            }

            $specData['baojia_list'] = $baojia_list;
            $specData['shangjia_list'] = $shangjia_list;

           

            $specData = json_encode($specData);
        }else{

            $spec_baojia = [];
            $spec_xiangou = [];
            $spec_dinghuo = [];

            $spec = json_decode(json_encode($row['spec']),true);
            if (!empty($spec[0]['baojia'])) {
                $spec[0]['baojia'] = json_decode($spec[0]['baojia'],true);
            }else{
                $spec[0]['baojia'] = [];
            }
             if (!empty($spec[0]['xiangou'])) {
                $spec[0]['xiangou'] = json_decode($spec[0]['xiangou'],true);
            }else{
                $spec[0]['xiangou'] = [];
            }
             if (!empty($spec[0]['dinghuo'])) {
                $spec[0]['dinghuo'] = json_decode($spec[0]['dinghuo'],true);
            }else{
                $spec[0]['dinghuo'] = [];
            }

            if (!empty($spec[0]['baojia_quyu'])) {
                $spec[0]['baojia_quyu'] = json_decode($spec[0]['baojia_quyu'],true);
            }else{
                $spec[0]['baojia_quyu'] = [];
            }

            foreach ($baojia as $key => $value) {
                $spec_baojia[$value['id']] = 0;
                $spec_xiangou[$value['id']] = 0;
                $spec_dinghuo[$value['id']] = 1;
                
                if (isset($spec[0]['baojia'][$value['id']])) {
                    $spec_baojia[$value['id']] = $spec[0]['baojia'][$value['id']];
                }
                if (isset($spec[0]['xiangou'][$value['id']])) {
                        $spec_xiangou[$value['id']] = $spec[0]['xiangou'][$value['id']];
                }
                if (isset($spec[0]['dinghuo'][$value['id']])) {
                    $spec_dinghuo[$value['id']] = $spec[0]['dinghuo'][$value['id']];
                }
            }  


            foreach ($shangjia as $key => $value) {
                $spec_baojia2[$value['id']] = 0;
                $shangjia[$key]['baojia'] = 0;
              
                if (isset($spec[0]['baojia_quyu'][$value['id']])) {
                    $spec_baojia2[$value['id']] = $spec[0]['baojia_quyu'][$value['id']];
                }
                $shangjia[$key]['baojia'] =  $spec_baojia2[$value['id']];
               
            }
            
           
            foreach ($baojia2 as $key => $value) {
               $baojia2[$key]['baojia'] = $spec_baojia[$value['id']];
               $baojia2[$key]['xiangou'] = $spec_xiangou[$value['id']];
               $baojia2[$key]['dinghuo'] = $spec_dinghuo[$value['id']];
            }
            
        }
       

        $this->view->assign("shangjia", $shangjia);
        $this->view->assign("baojia2", $baojia2);

        $row['specData'] = $specData;
        $row = json_decode(json_encode($row),true);

        if (!empty($row['category_id'])) {
            $row['category_id'] = explode(",", $row['category_id']);
            foreach ($row['category_id'] as $key => $value) {
                $row['category_id'][$key] = intval($value);
            }
        }
        

        $this->assignconfig('row', $row);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit2($ids = NULL)
    {
        $row = $this->model->get($ids, ['specRel', 'spec', 'spec_rel.spec']);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        //成功之后 存储商品规格
                        $spec_many_params = $this->request->post("spec_many/a");
                        $row->addGoodsSpec($params,$spec_many_params,$this->request->post("spec/a"), true);
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        // 多规格信息
        $specData = 'null';
        if ($row['spec_type'] === '20'){
            $specData = json_encode($this->model->getManySpecData($row['spec_rel'], $row['spec']));
        }
        $row['specData'] = $specData;
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit3($ids = NULL)
    {
        $row = $this->model->get($ids, ['specRel', 'spec', 'spec_rel.spec']);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = basename(str_replace('\\', '/', get_class($this->model)));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : true) : $this->modelValidate;
                        $row->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        //成功之后 存储商品规格
                        $spec_many_params = $this->request->post("spec_many/a");
                        $row->addGoodsSpec($params,$spec_many_params,$this->request->post("spec/a"), true);
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        // 多规格信息
        $specData = 'null';
        if ($row['spec_type'] === '20'){
            $specData = json_encode($this->model->getManySpecData($row['spec_rel'], $row['spec']));
        }
        $row['specData'] = $specData;
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    public function select()
    {
        if (!$this->request->isAjax()) {
            return $this->view->fetch();
        }

        $search = $this->request->request('search');
        $search = json_decode($search,true);
        if (!empty($search)) {
            // var_dump($search);

            if (!empty($search['id'])) {
                $map['fa_litestore_goods.goods_id'] = ['in',$search['id'][0]];
            }
            if (!empty($search['keyword'])) {
                $map['fa_litestore_goods.goods_name'] = ['like','%'.$search['keyword'][0].'%'];
            }
        }
        // var_dump($ids);
        $model_temp = new Wxlitestoregoods();
        $tableName = $model_temp->getTable();
        // 多规格商品 最高价与最低价
        $GoodsSpec = new Litestoregoodsspec();
        $minPriceSql = $GoodsSpec->field(['MIN(goods_price)'])
            ->where('goods_id', 'EXP', "= `$tableName`.`goods_id`")->buildSql();
        $maxPriceSql = $GoodsSpec->field(['MAX(goods_price)'])
            ->where('goods_id', 'EXP', "= `$tableName`.`goods_id`")->buildSql();
        $map['is_jifen'] = 0;
        $map['is_kan'] = 0;
        $map['is_zhekou'] = ['in',[0,2]];
        $listdata = $model_temp->where($map)->field(['*', '(sales_initial + sales_actual) as goods_sales',
            "$minPriceSql AS goods_min_price",
            "$maxPriceSql AS goods_max_price"
        ])->with(['spec']);
       $goods = $listdata->paginate(20);

       
        $this->success('获取成功', null, $goods);
    }


    public function md(){
        if($this->request->isPost())
        {   

            $param = $this->request->param();
            

            

            if (empty($param['goods_id'])) {
                $this->error('请选择商品');
            }

            $ids = explode(',',$param['goods_id']);

            $map['goods_id'] = ['in',$ids];
            $updata['shangjia_id'] = $param['shangjia_id'];


            Db::table('fa_litestore_goods')->where($map)->update($updata);

         
            $this->success();
        }

        $param = $this->request->param();

        $this->view->assign("ids", $param['ids']);
        return $this->view->fetch();
    }


    /**
     * 导入
     *
     * @return void
     * @throws PDOException
     * @throws BindParamException
     */
    public function import()
    {
        $file = $this->request->request('file');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, 'w');
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding !== 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                }
                $n++;
            }
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }

        //导入文件首行类型,默认是注释,如果需要使用字段名称请使用name
        $importHeadType = isset($this->importHeadType) ? $this->importHeadType : 'comment';

        $table = $this->model->getQuery()->getTable();
        $database = \think\Config::get('database.database');
        $fieldArr = [];
        $list = db()->query("SELECT COLUMN_NAME,COLUMN_COMMENT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = ? AND TABLE_SCHEMA = ?", [$table, $database]);
        foreach ($list as $k => $v) {
            if ($importHeadType == 'comment') {
                $v['COLUMN_COMMENT'] = explode(':', $v['COLUMN_COMMENT'])[0]; //字段备注有:时截取
                $fieldArr[$v['COLUMN_COMMENT']] = $v['COLUMN_NAME'];
            } else {
                $fieldArr[$v['COLUMN_NAME']] = $v['COLUMN_NAME'];
            }
        }

        //加载文件
        $insert = [];
        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            $fields = [];
            for ($currentRow = 2; $currentRow <= 2; $currentRow++) {
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $fields[] = $val;
                }
            }


            for ($currentRow = 3; $currentRow <= $allRow; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $values[] = is_null($val) ? '' : $val;
                }
                

                
                $temp = array_combine($fields, $values);
                $insert[] = $temp;
 
              
            }

          
        } catch (Exception $exception) {
            $this->error($exception->getMessage());
        }
        if (!$insert) {
            $this->error(__('No rows were updated'));
        }


        if (!empty($insert)) {
           foreach ($insert as $key => $value) {

                
                QueueApi::push('addons\faqueue\library\jobs\GoodsSave',$value,'dongping');
                 
            }
        }

      
        $this->success('上传成功,'.count($insert).'商品正在更新中');
    }

}
